package com.sunseen.intelligencebus.home

import android.media.Ringtone
import android.os.Bundle
import android.os.Vibrator
import android.util.Log
import android.widget.EditText
import android.widget.TextView
import androidx.databinding.ViewDataBinding
import com.sunseen.intelligencebus.base.AbsBindingFragment
import com.sunseen.intelligencebus.databinding.FragmentHomeBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import android.app.Service
import android.graphics.BitmapFactory
import android.media.RingtoneManager
import com.amap.api.location.AMapLocationClient
import com.amap.api.maps.AMap
import com.amap.api.maps.MapView
import com.sunseen.intelligencebus.ArriveAtStationEvent
import com.sunseen.intelligencebus.R
import com.amap.api.location.AMapLocationListener
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptor
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.sunseen.intelligencebus.riding.QrCodeRefershEvent
import java.text.SimpleDateFormat
import java.util.*


class HomeFragment : AbsBindingFragment() {

    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }

    override fun setLayout(): Int {
        return R.layout.fragment_home
    }

    lateinit var stationTv: TextView
    lateinit var peopleNumberTv: TextView
    lateinit var testMsgEdit: EditText
    lateinit var goalStationTv:TextView

    lateinit var mVibrator: Vibrator
    lateinit var mRingtone: Ringtone

    private lateinit var mapView: MapView
    private lateinit var aMap: AMap
    private lateinit var mLocationClient: AMapLocationClient

    private var lat: Double = 0.0
    private var lon: Double = 0.0
    //声明定位回调监听器
    private var mLocationListener: AMapLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.locationType//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.latitude//获取纬度
                amapLocation.longitude//获取经度
                amapLocation.accuracy//获取精度信息
                val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val date = Date(amapLocation.time)
                df.format(date)//定位时间
                amapLocation.address//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                amapLocation.country//国家信息
                amapLocation.province//省信息
                amapLocation.city//城市信息
                amapLocation.district//城区信息
                amapLocation.street//街道信息
                amapLocation.streetNum//街道门牌号信息
                amapLocation.cityCode//城市编码
                amapLocation.adCode//地区编码
                amapLocation.aoiName//获取当前定位点的AOI信息
                lat = amapLocation.latitude
                lon = amapLocation.longitude
                Log.v("pcw", "lat : $lat lon : $lon")

                aMap.clear()
                // 设置当前地图显示为当前位置
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(lat, lon), 19f))
                var markerOptions = MarkerOptions()
                markerOptions.position(LatLng(lat, lon))
                markerOptions.title("当前位置")
                markerOptions.visible(true)
                var bitmapDescriptor: BitmapDescriptor = BitmapDescriptorFactory.fromBitmap(
                    BitmapFactory.decodeResource(getResources(), R.drawable.png_location_green_64)
                )
                markerOptions.icon(bitmapDescriptor)
                aMap.addMarker(markerOptions)
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e(
                    "AmapError", "location Error, ErrCode:"
                            + amapLocation.errorCode + ", errInfo:"
                            + amapLocation.errorInfo
                )
            }
        }
    }

    //声明mLocationOption对象
    var mLocationOption: AMapLocationClientOption? = null

    override fun onBindView(viewDataBinding: ViewDataBinding, bundle: Bundle?) {
        EventBus.getDefault().register(this)
        mVibrator = activity!!.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
        val notifyUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        mRingtone = RingtoneManager.getRingtone(context, notifyUri)
        val binding = viewDataBinding as FragmentHomeBinding
        stationTv = binding.currentStationTv
        peopleNumberTv = binding.peopleNumberTv
        goalStationTv = binding.goalStationTv
        testMsgEdit = binding.msgEdit
        binding.testSendMsgBtn.setOnClickListener {
            Log.e("test", "testSendMsgBtn OnClick")
            EventBus.getDefault().post(ArriveAtStationEvent(false, "应科院"))
        }

        mapView = binding.mapView
        mapView.onCreate(bundle)// 此方法必须重写
        aMap = mapView.map
        //初始化定位
        mLocationClient = AMapLocationClient(activity?.application)
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener)
        aMap = mapView.getMap()
        setUpMap()
    }

    private fun setUpMap() {
        //初始化定位参数
        mLocationOption = AMapLocationClientOption()
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption?.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption?.setNeedAddress(true)
        //设置是否只定位一次,默认为false
        mLocationOption?.setOnceLocation(false)
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption?.setWifiActiveScan(false)
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption?.setMockEnable(false)
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption?.setInterval(2000)
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption)
        //启动定位
        mLocationClient.startLocation()
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBusMsgGot(event: BusMsgGotEvent) {
        for (b in event.bytes) {
            refreshText(b)
        }
    }

    private fun refreshText(b: Byte) {
        if (b > 100) {
            if (b > 110) {
                stationTv.text = getStationStr((b.toInt() - 46).toChar())
            } else {
                stationTv.text = getStationStr((b.toInt() - 36).toChar())
            }

        } else {
            peopleNumberTv.text = b.toInt().toString()
        }
    }

    private fun getStationStr(stationChar: Char): String {
        var stationStr = "未知"
        when (stationChar) {
            'A' -> stationStr = "火车站"
            'B' -> stationStr = "广场站"
            'C' -> stationStr = "汽车站"
            'D' -> stationStr = "二中站"
            'E' -> stationStr = "应科站"
            'F' -> stationStr = "附医站"
        }
        return stationStr
    }

    override fun onResume() {
        super.onResume()
        mapView.onResume()
    }


    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }

    override fun onStop() {
        super.onStop()
        mLocationClient.stopLocation();//停止定位
    }

    override fun onDestroy() {
        super.onDestroy()
        mapView.onDestroy()
        //销毁定位客户端。
        mLocationClient.onDestroy()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onrefeshQrcode(event: QrCodeRefershEvent) {
        when(event.stationId){
            0 -> goalStationTv.text = "火车站"
            1 -> goalStationTv.text = "广场站"
            2 -> goalStationTv.text = "汽车站"
            3 -> goalStationTv.text = "二中站"
            4 -> goalStationTv.text = "应科站"
            5 -> goalStationTv.text = "附医站"
        }
    }
}
